package com.hnx.admin.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.hnx.admin.annonation.LoginValid;
import com.hnx.admin.api.service.cache.CacheAPI;
import com.hnx.admin.jwt.JwtUtil;
import com.hnx.admin.redis.RedisCache;
import com.hnx.admin.security.utils.SecurityUtil;
import com.hnx.admin.system.domain.convert.user.UserConvert;
import com.hnx.admin.system.domain.dto.user.UserDTO;
import com.hnx.admin.system.domain.param.user.query.LoginBody;
import com.hnx.admin.system.domain.vo.role.RoleVO;
import com.hnx.admin.system.domain.vo.user.UserDetailVO;
import com.hnx.admin.system.domain.vo.user.UserVO;
import com.hnx.admin.system.mapper.user.UserMapper;
import com.hnx.admin.system.service.MenuService;
import com.hnx.admin.system.service.UserService;
import com.hnx.admin.utils.ServletUtil;
import com.hnx.admin.web.exception.UserNotExistsException;
import com.hnx.admin.web.json.ResultJson;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/*
项目名称： core
创 建 人: 倔强的头发
创建日期： 2025/5/26   19:33:46 
描   述：
*/
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService, CacheAPI {
    private final UserMapper userMapper;
    private final UserConvert userConvert;
    private final JwtUtil jwtUtil;
    private final JwtHandler jwtHandler;
    private final MenuService menuService;
    private final RedisCache redisCache;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDTO userDTO = userMapper.selectUserByUsername(username).orElseThrow(UserNotExistsException::new);
        UserVO user = userConvert.toVO(userDTO);
        return new UserDetailVO(user,menuService.getPermissions(user));
    }
    @Lazy
    @Autowired
    private AuthenticationManager authenticationManager;
    @Override
    @LoginValid
    public ResultJson login(LoginBody loginBody) {

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginBody.getUsername(), loginBody.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        UserDetailVO userDetailVO = (UserDetailVO) authenticate.getPrincipal();
        Map<String,String> map = new HashMap<>();
        map.put("uuid",  loginBody.getUuid());
        String token = jwtUtil.createToken(map);
        jwtHandler.refreshToken(userDetailVO,getTokenKey(loginBody.getUuid()));
        return ResultJson.success().add("token", token);
    }

    @Override
    public ResultJson getInfo() {
        HttpServletRequest request = ServletUtil.getRequest();
        Object principal = SecurityUtil.getPrincipal();
        String userKey = jwtUtil.getUserKey(request);
        UserDetailVO userDetailVO = redisCache.getCacheObject(userKey, UserDetailVO.class);
        if (ObjectUtil.isNotEmpty(userDetailVO)){
            return ResultJson.success().add("roles", userDetailVO.getUserVO().getRoleList().stream().map(RoleVO::getRoleId)).add("permissions",  userDetailVO.getPermission()).add("user",userDetailVO.getUserVO());
        }
        return ResultJson.fail();
    }


}
